/**
 * @author: qwesde@hust.edu.cn
 * @date: 2021/2/6 1:29
 */

import axios from 'axios'
import store from '../store'
import {getToken} from "./auth";
import {Message, MessageBox} from "element-ui";

// 使用axios发送客户端的请求
const client = axios.create({
    baseURL: process.env.BASE_API,
    timeout: 15000
});

// request拦截器，设置token
client.interceptors.request.use(config => {
    if (store.getters.token) {
        config.headers['token'] = getToken()
    }
    return config
}, error => {
    console.log(error)
    return Promise.reject(error)
})
// response 拦截器
client.interceptors.response.use(response => {
    const res = response.data;
    // 业务api接口200表示ok
    if (res.code !== 200) {
        Message({
            message: res.msg,
            type: "error",
            duration: 3 * 1000
        })
        return Promise.reject("error");
    }
    // 401:未登录
    if (res.code === 401) {
        MessageBox.confirm('你被登出，可以取消继续留在该页面，或者重新登陆','确定登出', {
            confirmButtonText: '重新登陆',
            cancelButtonText: '取消',
            type: "warning"
        }).then(() => {
            store.dispatch("Logout").then(() => {
                location.reload();
            })
        })
        return Promise.reject('error')
    } else {
      return res;
    }
}, error => {
    console.log(error)
    Message({
        message: error.msg,
        type: "error",
        duration: 3000
    })
    return Promise.reject(error)
})

export default client;
